/**
 * 移动浏览器端js公共脚本程序
 * 2017年12月26日 星期二
 */
import {Aurora} from './Aurora'
import Pager from './wap/Pager'
import AutoLogin from './wap/AutoLogin'
import Form from './Form'
var instance;
// Wap UI 内部实例
let WapWeUiLoadingInstance = null;
class Wap extends Aurora{
    constructor(){
        super()
        this._homeUrl = this._baseurl + 'wap.html'     // 首页
        this._wapurl = this._baseurl + 'wap/'        //  wap 基础页面
    }
    /**
     * 生成 wap 项目的url
     * @param {string} url
     * @param {bool} suffix
     * @return {string}
     */
    getWapUrl(url, suffix){
        return this._wapurl + url + (suffix? '.html': '')
    }
    // 表单检测标红与清除
    CellWarning(dom,clear) {
        var cell = dom.parent('div.weui-cell');
        var cellFt = cell.find('.weui-cell__ft');
        if(clear){
            // 清除警告
            cell.removeClass('weui-cell_warn');
            if(cellFt.length>0) cellFt.remove();
        }else{
            cell.addClass('weui-cell_warn');
            if(cellFt.length == 0){
                var xhtml = '<div class="weui-cell__ft"><i class="weui-icon-warn"></i></div>';
                cell.after(xhtml);
            }
        }
    }
    /**
     * 操作成功是返回信息
     * @param msg
     * @param title 标题 可选
     * @param url 返回地址可选, 服从 urlBuild生成规则
     */
    msg_success(msg,title,url) {
        var jsondata = {desc:msg};
        if(title) jsondata.title = title;
        if(url) jsondata.url = url;
        this.post(this._baseurl+'wap/msg/succs.html',jsondata);
    }
    /**
     * weui from 表单检测
     * @param dom
     * @param type   C/W/S -> clear,warning,success
     * @returns {boolean}
     * @constructor
     */
    WeuiFromCheck(dom,type) {
        var cell = dom.parents('.weui-cell');
        var cellFt = cell.find('.weui-cell__ft');
        if(type == 'C'){
            if(cellFt.length > 0){
                cellFt.remove();
                return true;
            }
            return false;
        }
        var xhtml = '';
        if (type == 'W') {
            xhtml = '<i class="fa fa-warning text-warning"></i>';
        } else xhtml = '<i class="fa fa-check text-success"></i>';
        if (cellFt.length > 0) cellFt.html(xhtml);
        else cell.append('<div class="weui-cell__ft">' + xhtml + '</div>');
    }
    /**
     * 有滑动时返回，需要引入 zepto/touch.js
     * @param url 调整地址  string/function
     * @param callback 回调函数 function
     */
    SwipeRightBack(url,callback) {
        if(typeof url == 'function'){
            callback = url;
            url = null;
        }
        url = url? url:'finance.html';
        // 右滑动时返回
        $(document).swipeRight(function () {
            if(typeof callback == 'function'){
                if(!callback()) return;
            }
            location.href = Wap._wapurl + url;
        });
    }
    /**
     * weui.js 扩展
     */
    loading (msg, timeout, callback){
        msg = msg? msg: '数据提交中……';
        var $loading = weui.loading(msg);
        timeout = timeout? timeout: 15*1000;  //15s
        callback = callback|| function(){        
            weui.alert('数据请求出错！');
        };
        setTimeout(function(){
            $loading.hide(callback);
        }, timeout);
        return $loading;
    }
    /**
     * 跳转到顶部控件
     */
    forwardTopScroll(callback){   
        var selector = 'string' == typeof(callback)? $(callback): false;
        var gTop = function(){return false;};
        if('function' != typeof(callback)){
            var $el = false;
            // 获取元素
            if(selector && selector.length>0){
                $el = selector[0];
                gTop = function(){
                    $el.scrollTop = 0;
                    return true;
                };
            }
            callback = function(){
                // 获取元素
                if($el){
                    gTop();
                }
            };
            
        }
        $('.aurora-forward-top a').click(callback);
        var $forward = {
            hide: function(){
                $('.aurora-forward-top').addClass('aurora-hidden');
            },
            show: function(){
                $('.aurora-forward-top').removeClass('aurora-hidden');
            },
            top: gTop
        };
        return $forward;
    }

    /**
     * @param selector
     * @returns {AmTag}
     */
    amTag(selector){
        return new AmTag(selector);
    }

    /**
     *  移动端 popop 窗口实现
     * @param {string} selector
     * @param {string|object} urls 可选参数选项： {url, send:{}, valueKey: 'value', idKey: 'id', nameKey: 'name'}
     * @param {function} callback 点击以后的处理数据: callback(id, rs)
     */
    popop(selector, urls, callback){
        return new Poppp(selector, urls, callback);
    }

    /**
     * 基于 popop 的 tags 生成器
     * @param selector
     * @param urls
     * @return {TagsByPopop}
     */
    tags(selector, urls){
        return new TagsByPopop(selector, urls);
    }

    /**
     * weui.loading 管理，用于实现全局关闭
     * @param {string|null} msg
     * @param fn
     */
    weuiLoading(msg, fn){
        fn = fn && 'function' === typeof fn? fn : null;
        if(WapWeUiLoadingInstance){
            if(fn){
                WapWeUiLoadingInstance.hide(fn);
            }else {
                WapWeUiLoadingInstance.hide();
            }
        }
        if(msg){
            WapWeUiLoadingInstance = weui.loading(msg);
            return WapWeUiLoadingInstance;
        }
        return null;
    }
}

/**
 * And Mobile Tag (By Joshua Conero)
 */
class AmTag {
    constructor(selector){
        this.selector = selector || '.tag-groups';
        this._def = '';
    }

    /**
     * @param value
     */
    set def(value){
        this._def = value;
        return this;
    }
    /**
     * 开启 am tag
     */
    useAmTag(){
        let selector = this.selector;
        let se = $(selector);
        let _amtag = this;
        se.find('a.am-tag').off('click').on('click', function () {
            se.find('a.am-tag-active').removeClass('am-tag-active').addClass('am-tag-normal');
            let el = $(this);
            el.removeClass('am-tag-normal').addClass('am-tag-active');
            _amtag._currentTagCol = el.data('col');
        });
    }

    /**
     * 生成 html 数据
     * @param {Object} data
     * @returns {string}
     */
    getHtml(data){
        let xh = '';
        let def = this._currentTagCol || this._def;
        if(def){
            this._currentTagCol = def;
        }
        for (let k in data){
            let defS = def && k === def? 'am-tag-active': 'am-tag-normal';
            xh += `<a href="javascript:;" data-col="${k}" class="am-tag ${defS}">${data[k]}</a>`;
        }
        xh = `<div class="tag-groups">${xh}</div>`;
        return xh;
    }

    /**
     * @returns {string}
     */
    get col(){
        return this._currentTagCol;
    }
}


/**
 * 移动版 popop 弹出窗
 */
class Poppp {
    /**
     *  移动端 popop 窗口实现
     * @param {string} selector
     * @param {string|object} urls 可选参数选项： {url, send:{}, valueKey: 'value', idKey: 'id', nameKey: 'name'}
     * @param {function} callback 点击以后的处理数据: callback(id, name, cache)
     */
    constructor(selector, urls, callback){
        this.agent = 'object' === typeof selector? selector: $(selector);
        this.urls = urls;
        this.callback = callback;
    }

    /**
     * 生成
     */
    create(){
        let {agent, urls, callback} = this;
        let cell = agent.parents('div.weui-cell'),
            url,
            send = {},
            id = 'id',
            name = 'name',
            valKey = 'value'
        ;
        let inst = this;
        // 类型判断
        if(typeof urls === 'string'){
            url = urls;
        }else if(typeof urls === 'object'){
            url = urls.url;
            send = urls.send || {};
            id = urls.idKey || '';
            name = urls.nameKey || '';
            valKey = urls.valueKey || '';
        }

        /**
         * 选择器渲染处理
         * @param value
         */
        var doRenderChoiseFn = function(value){
            // 宿主 DOM 对象检测/生成
            let choice = cell.next('.jc-search-choice');
            inst.popWin = choice;   // 弹出框
            if(choice.length === 0){
                cell.after(`<div class="weui-cells jc-search-choice" style="display: block; transform-origin: 0px 0px; opacity: 1; transform: scale(1, 1);">
            </div>`);
                choice = cell.next('.jc-search-choice');
            }
            if(!value){
                choice.html('');
                return;
            }
            send[valKey] = value;
            instance.ApiRequest(url, send, function (rs) {
                if(rs.code === 1) {
                    let {data} = rs;
                    let html = '';
                    let {result} = data;
                    for (var i = 0; i < result.length; i++) {
                        let dd = result[i];
                        html += `
                        <a class="weui-cell weui-cell_access" data-id="${dd[id]}" data-cache="${Base64.encode(JSON.stringify(dd))}" data-name="${dd[name]}">
                            <div class="weui-cell__bd weui-cell_primary">
                                <p>${dd[name]}</p>
                            </div>
                        </a>
                    `;
                    }

                    choice.html(html);
                    choice.find('a').click(function () {
                        let a = $(this);
                        let ccData = a.data('cache');
                        if(ccData){
                            ccData = Base64.decode(ccData);
                        }
                        ccData = ccData? JSON.parse(ccData) : null;
                        callback(a.data('id'), a.data('name'), ccData);
                    });
                }
            });
        };
        // 键盘处理事件
        agent.keydown(function () {
            let $this = $(this);
            doRenderChoiseFn($this.val().trim());
        });
    }

    /**
     * 关闭窗口
     * @return {Poppp}
     */
    clear(){
        let {popWin} = this;
        if(popWin){
            popWin.html('');
        }
        return this;
    }
}


/**
 * 基于 popop 的 tags 列表生成器
 */
class TagsByPopop {
    constructor(selector, param){
        this.input = 'object' === typeof selector? selector: $(selector);   // 输入框
        let cell = this.input.parents('.weui-cell');
        let jctag = cell.prev('.jc-tag-list');
        if(jctag.length === 0){
            cell.before('<div class="jc-tag-list"></div>');
            jctag = this.input.parents('.weui-cell').prev('.jc-tag-list');
        }
        this.jctag = jctag;
        this.param = param;
    }

    /**
     * tag 创建创建
     * @param data
     */
    create(data){
        let cInst = this;
        this.popop = new Poppp(this.input, this.param, (id, name, cache) => {
            cInst.add(name, id);
            this.popop.clear();
            this.input.val('');
        });
        this.popop.create();
        this.input.keydown(function (evt) {
            // enter
            if (evt.keyCode === 13){
                let $this = $(this),
                    vtag = $this.val()
                ;
                if(vtag){
                    cInst.add(vtag);
                    $this.val('');
                }
            }
        });
        // tag 显示
        if(data){
            for(let id in data){
                this.add(data[id], id);
            }
        }
    }

    /**
     * 添加标签
     * @param {string} name
     * @param {string} id
     */
    add(name, id){
        if(!name){
            return;
        }
        let cInst = this;
        // 检测是否已经存在 tag
        if (id && this.jctag.find(`[data-id="${id}"]`).length > 0) {
            return;
        }else if (this.jctag.find(`[data-name="${name}"]`).length > 0 ){
            return;
        }
        let idAttr = id? ` data-id="${id}"`:'';
        this.jctag.append(`
            <a class="weui-btn weui-btn_mini weui-btn_plain-primary jc-tag-item" href="javascript:;" data-name="${name}"${idAttr}>
                ${name}
                <span class="weui-badge" style="position: absolute;top: -0.1em;right: -0.1em; display: none;z-index: 10;font-size: 1.1em;">×</span>
            </a>
        `);
        // 显示可删除tag控件
        let aTag = this.jctag.find('.jc-tag-item');
        aTag.off('mouseover').on('mouseover', function () {
            cInst.jctag.find('.weui-badge').hide();
            $(this).find('.weui-badge').show();
        });
        aTag.off('mouseout').on('mouseout', function () {
            cInst.jctag.find('.weui-badge').hide();
        });
        // 移除标签
        aTag.find('.weui-badge').off('click').on('click', function () {
            let $this = $(this);
            $this.parents('.jc-tag-item').remove();
        });
    }

    /**
     * 获取数据
     * @return {object} 保存的数据，以及数据格式： [{id, name}]
     */
    get data(){
        let {jctag} = this;
        let tagItem = jctag.find('a.jc-tag-item');
        var data = [];
        for (let i = 0; i < tagItem.length; i++) {
            let item = $(tagItem[i]),
                id = item.data('id'),
                name = item.data('name');
            let dd = {name};
            if(id){
                dd.id = id;
            }
            data.push(dd);
        }
        return data;
    }
}
// 数据实例化对象
instance = new Wap

/**
 * @return {object} => {this.loging/this.add}
 */
instance.autoLogin = function(){
    return new AutoLogin(instance)
}

// 表单处理项
instance.Extends(Form)

// export default {
//     instance,
//     Pager
// }

export {instance}
export {Pager}